<?
    require_once(SITE_PATH.'configs/payment_alertpay.conf.php');

    class AlertPay_ipn_processor
    {
        var $ID   = 'alertpay';
        var $type = 'redirect';

        var $debug_email = 'bienko@cupid.com';

        function process($CC, $type = 'subscription', $mode = 'live')
        {
            global $AlertPayAccounts;

            $siteID         = $CC['siteID'];
            if (empty($AlertPayAccounts[$siteID])) $siteID = 0;
            $EmailMerchant  = $AlertPayAccounts[$siteID]['cfg_EmailMerchant'];

            $post_url = 'https://www.alertpay.com/PayProcess.aspx';

            if ($type == 'subscription' && !empty($CC['repeat'])){
                if ($CC['repeat']) $CC['amount'] = $CC['repeat']['amount'];
                echo '<html><body>';
                echo '<form action="' . $post_url . '" name="form1" method="post">';
                echo '<input type="hidden" name="ap_merchant"       value="' . $EmailMerchant .'" /> ';
                echo '<input type="hidden" name="ap_purchasetype"   value="' . 'subscription' .'" /> ';
                echo '<input type="hidden" name="ap_itemname"       value="' . $CC['product'] .'" /> ';
                echo '<input type="hidden" name="ap_amount"         value="' . $CC['amount'] .'" /> ';
                echo '<input type="hidden" name="ap_currency"       value="' . $CC['currency'] .'" /> ';
                echo '<input type="hidden" name="ap_returnurl"      value="' . SITE_URL.'/alertpay.php' . '" /> ';
                echo '<input type="hidden" name="ap_cancelurl"      value="' . SITE_URL.'/alertpay.php?action=cancel' . '" /> ';
                echo '<input type="hidden" name="ap_timeunit"       value="' . $CC['repeat']['period'] . '" /> ';
                echo '<input type="hidden" name="ap_periodlength"   value="' . $CC['repeat']['interval'] . '" /> ';
                if (!empty($CC['repeat']['periodcount'])){
                  echo '<input type="hidden" name="ap_periodcount"  value="' . $CC['repeat']['periodcount'] . '" /> ';
                }
                if ($CC['trial']){
                  echo '<input type="hidden" name="ap_trialtimeunit"      value="' . $CC['trial']['period'] . '" /> ';
                  echo '<input type="hidden" name="ap_trialperiodlength"  value="' . $CC['trial']['interval'] . '" /> ';
                  echo '<input type="hidden" name="ap_trialamount"        value="' . $CC['trial']['amount'] . '" /> ';
                }
                echo '<input type="hidden" name="apc_1"             value="' . $CC['userid'] . '" /> ';
                echo '<input type="hidden" name="apc_2"             value="' . $CC['record_id'] . '" /> ';
                echo '<input type="hidden" name="apc_3"             value="' . $CC['siteID'] . '" /> ';
                echo '</form>';
                echo '<script>document.form1.submit()</script>';
                echo '</body></html>';
                die;
            }else{
                echo '<html><body>';
                echo '<form action="' . $post_url . '" name="form1" method="post">';
                echo '<input type="hidden" name="ap_merchant"       value="' . $EmailMerchant .'" /> ';
                echo '<input type="hidden" name="ap_purchasetype"   value="' . 'service' .'" /> ';
                echo '<input type="hidden" name="ap_itemname"       value="' . $CC['product'] .'" /> ';
                echo '<input type="hidden" name="ap_amount"         value="' . $CC['amount'] .'" /> ';
                echo '<input type="hidden" name="ap_currency"       value="' . $CC['currency'] .'" /> ';
                echo '<input type="hidden" name="ap_returnurl"      value="' . SITE_URL.'/alertpay.php' . '" /> ';
                echo '<input type="hidden" name="ap_cancelurl"      value="' . SITE_URL.'/alertpay.php?action=cancel' . '" /> ';
                echo '<input type="hidden" name="apc_1"             value="' . $CC['userid'] . '" /> ';
                echo '<input type="hidden" name="apc_2"             value="' . $CC['record_id'] . '" /> ';
                echo '<input type="hidden" name="apc_3"             value="' . $CC['siteID'] . '" /> ';
                echo '</form>';
                echo '<script>document.form1.submit()</script>';
                echo '</body></html>';
                die();
            }
        }

        function refund(&$CC, $mode = 'live')
        {
            global $AlertPayAccounts;

            $siteID         = $CC['siteID'];
            if (empty($AlertPayAccounts[$siteID])) $siteID = 0;
            $EmailMerchant  = $AlertPayAccounts[$siteID]['cfg_EmailMerchant'];
            $APIPassword    = $AlertPayAccounts[$siteID]['cfg_APIPassword'];

            $params = array(
                    'USER'                  => $EmailMerchant,
                    'PASSWORD'              => $APIPassword,
                    'TRANSACTIONREFERENCE'  => $CC['reference'],
                    'TESTMODE'              => ($mode=='live')?0:1,
            );

            $postipn = '';
            foreach ($params as $k=>$v)
            {
               if ($postipn) $postipn .= '&';
               $postipn .= $k.'='.urlencode($v);
            }

            $ch = curl_init(); 

            $posturl = 'https://api.alertpay.com/svc/api.svc/RefundTransaction';

            curl_setopt($ch, CURLOPT_URL, $posturl);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt($ch, CURLOPT_POST, 1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postipn);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

            $res = curl_exec($ch);

            $curl_error = curl_error($ch);

            if ($curl_error)
            {
               $curl_info = curl_getinfo($ch);

               return array(
                              'charged'  => false,
                              'apr_code' => '',
                              'reason'   => 'FAULT:<pre>'.print_r($curl_info, true).'</pre>',
                              'response' => '',
                              'order_id' => 0,
                           );
            }

            parse_str($res, $result);

            if (!empty($this->debug_email))
                @mail($this->debug_email, 'AlertPay.Refund', 'user_id : '.$CC['user_id']."\n".'order_id : '.$CC['orderid']."\n\n".print_r($result, true));

            $CC['note'] .= print_r($result, true);
            $CC['TRANSACTIONID'] = $result['REFERENCENUMBER'];

            if ($result['RETURNCODE']==100){
                $this->confirm($CC, 'refund');
            }else{
                $this->decline($CC, 'refund');
            }

            return $result;
        }

        function VerifyResponse($IPN, $verify_by_ip = false)
        {
            global $AlertPayAccounts, $AlertPayAllowedIP;

            $siteID          = $IPN['apc_3'];
            if (empty($AlertPayAccounts[$siteID])) $siteID = 0;
            $IPNSecurityCode = $AlertPayAccounts[$siteID]['cfg_IPNSecurityCode'];

            if ($IPN['ap_securitycode']==$IPNSecurityCode){
                if ($verify_by_ip && is_array($AlertPayAllowedIP) && !in_array($_SERVER['HTTP_X_FORWARDED_FOR'], $AlertPayAllowedIP)){
                    trigger_error("AlertPay: access is not allowed from IP {$_SERVER['HTTP_X_FORWARDED_FOR']}", E_USER_WARNING);
                    return false;
                }
                return true;
            }else return false;
        }

       function confirm($CC, $trans_type = 'process')
       {
           $objDB  = New DatingDB();
           $objSQL = New SQL();

           if ($trans_type=='process')
           {
                $objSQL->create("UPDATE orders SET
                                              apr_code             = :s:apr_code:,
                                              note                 = :s:note:,  
                                              reference            = :s:reference:
                                      WHERE
                                              id = :i:order_id:", 
                                      array(
                                              'apr_code'           => 'CHARGED',
                                              'note'               => $CC['note'],
                                              'reference'          => $CC['TRANSACTIONID'],
                                              'order_id'           => $CC['orderid'],
                                           )
                          );
                $objDB->execute($objSQL);
           }
           elseif ($trans_type=='refund')
           {
                $objSQL->create("UPDATE orders SET
                                              apr_code             = :s:apr_code:,
                                              note = CONCAT(note, '\n\nRefund response\n', :s:note:)
                                      WHERE
                                              id = :i:order_id:", 
                                      array(
                                              'apr_code'           => 'REFUNDED',
                                              'note'               => $CC['note'],
                                              'order_id'           => $CC['orderid'],
                                           )
                          );
                $objDB->execute($objSQL);
           }
       }

       function decline($CC, $trans_type = 'process')
       {
           $objDB  = New DatingDB();
           $objSQL = New SQL();

           if ($trans_type=='process')
           {
                $objSQL->create("UPDATE orders SET
                                              apr_code             = :s:apr_code:,
                                              note                 = :s:note:,
                                              reference            = :s:reference:
                                      WHERE
                                              id = :i:order_id:",
                                      array(
                                              'apr_code'           => 'DECLINED',
                                              'note'               => $CC['note'],
                                              'reference'          => $CC['TRANSACTIONID'],
                                              'order_id'           => $CC['orderid'],
                                           )
                          );
                $objDB->execute($objSQL);
           }
           elseif ($trans_type=='refund')
           {
                $objSQL->create("UPDATE orders SET
                                              note = CONCAT(note, '\n\nRefund response\n', :s:note:)
                                      WHERE
                                              id = :i:order_id:",
                                      array(
                                              'note'               => $CC['note'],
                                              'order_id'           => $CC['orderid'],
                                           )
                          );
               $objDB->execute($objSQL);
           }
       }

       function getXMLResponse($response)
       {
          if (empty($response) || !is_array($response)) return false;

          $result ="
              <Response>
                  <RETURNCODE>{$response['RETURNCODE']}</RETURNCODE>
                  <REFERENCENUMBER>{$response['REFERENCENUMBER']}</REFERENCENUMBER>
                  <DESCRIPTION>{$response['DESCRIPTION']}</DESCRIPTION>
                  <TESTMODE>{$response['TESTMODE']}</TESTMODE>
              </Response>";

           return $result;
       }

       function storeAccountID($orderID, $accountID)
       {
           $objDB  = New DatingDB();
           $objSQL = New SQL();

           $objSQL->create('
                UPDATE orders
                SET
                    accountID = :s:accountID:
                WHERE id = :i:order_id:',
                array(
                    'accountID' => $accountID,
                    'order_id'  => $orderID,
                )
           );
           $objDB->execute($objSQL);
       }

    }
?>